package com.quizh.euro.server.ws;

import java.util.logging.Logger;

import javax.inject.Provider;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;
import org.apache.shiro.web.util.WebUtils;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.quizh.euro.server.user.BaseServlet;
import com.quizh.euro.server.ws.exception.PermissionException;
import com.quizh.euro.user.bean.GaeUser;
import com.quizh.euro.user.dao.GaeUserDAO;

@Path("reg")
public class RegisterWs extends BaseServlet{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
    static final Logger LOG = Logger.getLogger(RegisterWs.class.getName());

	protected RegisterWs(Provider<GaeUserDAO> daoProvider) {
		super(daoProvider);
	}

	// these 4 are from jQuery.dataTables
    String DATATABLE_ECHO = "sEcho";
    String DATATABLE_START = "iDisplayStart";
    String DATATABLE_LENGTH = "iDisplayLength";
    String DATATABLE_SEARCH = "sSearch";

    String DELETE = "delete";
    String FORGOT = "forgot";
    String INVALIDATE_CACHE = "invalidateCache";
    String PASSWORD = "password";
    String REGISTRATION_STRING = "registrationString";
    String REMEMBER_ME = "rememberMe";
    String SUSPEND = "suspend";
    String USERNAME = "username";
    String userBaseUrl = "http://localhost:8888";
	public void registerUser(@Context HttpServletRequest request) {

        try {
            GaeUserDAO dao = new GaeUserDAO();

            String userName = WebUtils.getCleanParam(request, USERNAME);
            boolean isForgot = Boolean.parseBoolean(WebUtils.getCleanParam(request, FORGOT));

            GaeUser user = dao.findUser(userName);
            if (!isForgot && user != null && user.isRegistered()) {
                // You can't add a user who's already registered
                throw new PermissionException();

//                issueJson(response, HTTP_STATUS_FORBIDDEN,
//                        MESSAGE, userName + " is already registered");
            }  else {
                // we override the user, any registration email should work though (as long as its valid)
                String registrationString = registrationString(userName);
                LOG.info("registration is " + registrationString);

                dao.saveRegistration(registrationString, userName);

                Queue queue = QueueFactory.getDefaultQueue();
                queue.add(TaskOptions.Builder
                        .withUrl(userBaseUrl + "/registermail")
                        .param(USERNAME, userName)
                        .param(FORGOT, Boolean.toString(isForgot))
                        .param(REGISTRATION_STRING, registrationString));

//                issueJson(response, HTTP_STATUS_OK,
//                        MESSAGE, "ok");
            }
        } catch (Exception e) {
            LOG.warning("Can't register: " + e.getMessage());
            throw new PermissionException();
//            issue(MIME_TEXT_PLAIN, HTTP_STATUS_INTERNAL_SERVER_ERROR,
//                  "Internal error: " + e.getMessage(), response);
        }
    
	}
	
    private String registrationString(String userName) {
        RandomNumberGenerator rng = new SecureRandomNumberGenerator();
        ByteSource salt = rng.nextBytes();
        return new Sha256Hash(userName, new SimpleByteSource(salt), 63).toHex().substring(0,10);
    }
	
	
}
